import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../services/auth-service';
import { Router } from '@angular/router';
import { MdlDialogService, MdlSnackbarService } from '@angular-mdl/core';
import { Observable } from 'rxjs/Observable';
import { SearchRet } from '../../shared/model/defination';
import { VisitService } from 'services/visit-service';
import { SessionService } from 'services/session-service';

@Component({
    selector: 'app-vist-cmp',
    templateUrl: './vist-cmp.component.html',
    styleUrls: ['./vist-cmp.component.scss'],
    providers: [AuthService, VisitService]
})
export class VistCmpComponent implements OnInit {
    // @ViewChild('confirmAlert')
    // public confirmAlert;
    public selected: Array<any> = [];
    public count = 0;
    public offset = 0;
    public limit = 10;
    public deleteId = 0;
    public isPageLoading = false;
    public rows = [];
    public pagerMessage = {
        emptyMessage: '没有数据',
        totalMessage: '总计'
    };
    public columns = [
        { name: 'Id', prop: 'id' },
        { name: '项目名称', prop: 'projectName' },
        { name: '所属城市', prop: 'city' },
        { name: '所属省份', prop: 'province' },
        { name: '所属辖区', prop: 'district' }
    ];

    get ProjectId() {
        // return 3;
        if (this._sessionService.isUserProperty) {
            return this._sessionService.Managable.id;
        }
        return null;
    }

    constructor(
        private _authService: AuthService,
        private _router: Router,
        private _dialogService: MdlDialogService,
        private _snackBarService: MdlSnackbarService,
        private _visitService: VisitService,
        private _sessionService: SessionService
    ) {}
    async ngOnInit() {
        this.page(this.offset, this.limit);
    }

    _constructQuery() {
        const criteria: any = {};
        if (this._sessionService.isUserProperty) {
            criteria.projectId = this._sessionService.Managable.id;
        }
        return criteria;
    }

    async page(offset, limit) {
        this.isPageLoading = true;
        // const criteria: any = {};
        try {
            const criteria: any = this._constructQuery();
            criteria.pageNumber = offset + 1;
            criteria.pageSize = this.limit;
            const action$ = <Observable<
                SearchRet<any>
            >>this._visitService.Search(criteria);
            const searchRet: any = await action$.toPromise();
            if (searchRet && searchRet.items) {
                searchRet.items.forEach(item => {
                    item.userName = item.user_name;
                    item.idCard = item.id_card;
                    item.startTime = item.start_time;
                    item.endTime = item.end_time;
                    item.visitCompany = item.visit_company;
                });
                console.log(searchRet.items);
            }
            this.count = searchRet.totalPageRecords;
            const start = offset * limit;
            const end = start + searchRet.items.length;
            // const rows = [...this.rows];
            // for (let i = start; i < end; i++) {
            //   rows[i] = searchRet.items[i - start];
            // }
            const rows = [...searchRet.items];
            this.rows = rows;
            this.isPageLoading = false;
            console.log('Page Results', start, end, rows);
        } catch (e) {
            if (e.status === 401) {
                this._router.navigate(['/login']);
            }
        } finally {
            this.isPageLoading = false;
        }
    }

    fetch(cb) {
        const req = new XMLHttpRequest();
        req.open('GET', `assets/projects.json`);

        req.onload = () => {
            cb(JSON.parse(req.response));
        };

        req.send();
    }

    async approve() {
        console.log(this.selected);
        const req = {
            project_id: this.ProjectId,
            ids: this.selected.map(s => s.id)
        };

        const resp = await this._visitService
            .approve(req.ids, req.project_id)
            .toPromise();

        if (resp) {
            this.selected = [];
        }
        console.log(resp);
    }

    async reject() {
        console.log(this.selected);
    }

    async onSelect($event) {
        console.log($event);
        this.selected = $event.selected;
    }

    async delete(id) {
        // try {
        //   await this._dialogService
        //     .confirm('确定删除此项目？', '取消', '确认')
        //     .toPromise();
        //   await this._projectService.Delete(+id).toPromise();
        //   await this.ngOnInit();
        // } catch (e) {
        //   this._snackBarService.showToast(e.message);
        // } finally {
        // }
    }

    onPage(event) {
        console.log('Page Event', event);
        this.page(event.offset, event.limit);
    }
}
